﻿namespace ChinaUnicom.Tasks
{
    using System;
    using System.Net;
    using Avatar.Schedule;

    public class LoginTask : ITask
    {
        string mobile, password, code;

        public LoginTask(string mobile, string password, string code)
        {
            this.mobile = mobile;
            this.password = password;
            this.code = code;
        }

        public void Start()
        {
            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }

            Factory.Operation.Login(mobile, password, code, s =>
            {
                if (AfterLogin != null)
                {
                    AfterLogin(this, EventArgs.Empty);
                }
                try
                {
                    if (s.Status == WebExceptionStatus.Success)
                    {
                        Authentication.Current.Signed = s.Result.Contains(mobile);
                        if (!Authentication.Current.Signed)
                        {
                            // 登录失败！
                            if (Failed != null)
                            {
                                Failed(this, new FailedEventArgs(this, new Exception(Factory.Parser.Failed(s.Result))));
                            }
                        }
                        else
                        {
                            Context.Current.Account.LastSigned = DateTime.Now;
                            if (Completed != null)
                            {
                                Completed(this, EventArgs.Empty);
                            }
                        }
                    }
                    else if (s.Exception != null && Failed != null)
                    {
                        Failed(this, new FailedEventArgs(this, s.Exception));
                    }
                    else if (Failed != null)
                    {
                        Failed(this, new FailedEventArgs(this, new Exception(Factory.Parser.Failed(s.Result))));
                    }
                }
                catch (Exception ex)
                {
                    if (Failed != null)
                    {
                        Failed(this, new FailedEventArgs(this, ex));
                    }
                }
            });
        }

        public int Delay { get { return 50; } }

        public bool IsUnique { get { return true; } }

        public event EventHandler Started;

        public event EventHandler Completed;

        public event EventHandler AfterLogin;

        public event EventHandler<FailedEventArgs> Failed;
    }
}
